package com.acme.bankapp.service.bank;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.acme.bankapp.domain.bank.Account;
import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.domain.bank.exceptions.ClientExistsException;

public class BankService {
	private static final String BANK_BACKUP_FILE = "sbuf.ser";

	public static void addClient (Bank bank, Client client) throws ClientExistsException {
		bank.addClient(client);
	}
	
	public static void printMaximumAmountToWithdraw(Bank bank) {
		for (Client cur: bank.getClients()) {
			System.out.println(cur.getClientSalutation());
			for (Account acc: cur.getAccounts()) {
				System.out.println(acc.maxAmountToWithdraw());
			}
		}
	}
	
	/**
	 * Bank backup service
	 * @param bank
	 * @throws IOException
	 */
	public static void saveBank (Bank bank) throws IOException {
		try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(BANK_BACKUP_FILE))) {
			
			oos.writeObject(bank);
		};
	}
	
	/**
	 * Service load bank from backup
	 * @return savedBank
	 * @throws ClassNotFoundException
	 * @throws IOException
	 */
	public static Bank readBank() throws ClassNotFoundException, IOException {
		Bank sb;
		try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(BANK_BACKUP_FILE))){
			sb = (Bank) ois.readObject();
		};
		return sb;
	}

}
